package com.htbb.common.msgBodyAdvice;

import com.alibaba.fastjson.JSON;
import com.htbb.common.base.MappingConfig;
import com.htbb.common.base.Result;
import com.htbb.common.util.security.AESUtil;
import com.htbb.model.personalInsure.dto.Channel;

import java.text.MessageFormat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 返回数据加密
 */
@ControllerAdvice
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice {
    private final static Logger logger = LoggerFactory.getLogger(EncryptResponseBodyAdvice.class);

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        /*根据注解判断是否需要加密*/
		boolean encode = false;
        if (returnType.getMethod().isAnnotationPresent(CryptionType.class)) {
        	CryptionType cryptionType = returnType.getMethodAnnotation(CryptionType.class);
            encode = cryptionType.encode();
        }
        
        if (encode) {
            try {
            	Result<Object> retObj = (Result<Object>)body;
            	/*有model数据时，才对model的值进行加密*/
            	Object modelData = retObj.getModel();
            	if(modelData != null){
            		String partnerCode = request.getHeaders().getFirst(DecryptAndCheckSignRequestBodyAdvice.partnerCodeParamName);
                	Channel channel = MappingConfig.getChannel(partnerCode.toUpperCase());
                	
            		String modelDataStr = JSON.toJSONString(modelData);
            		String channelInfo = MessageFormat.format( "【渠道id：{0}，名称：{1}】", partnerCode, channel.getName());
            		logger.info(channelInfo + "发送的响应model(未加密)：" + modelDataStr);
            		modelDataStr = AESUtil.aesEncrypt(modelDataStr, channel.getPassword(), "UTF-8");
            		logger.info(channelInfo + "发送的响应model(已加密)：" + modelDataStr);
            		Result<String> result = new Result<String>(retObj.getMsgCode(), retObj.getMsg());
            		result.setModel(modelDataStr);
            		return result;
            	}
            	
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            
        }
        return body;
    }
}
